package com.example.productmanagerspringboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.productmanagerspringboot.data.entity.Order;
import com.example.productmanagerspringboot.data.vo.OrderVO;
import com.example.productmanagerspringboot.data.vo.Response;
import com.example.productmanagerspringboot.mapper.OrderMapper;
import com.example.productmanagerspringboot.utils.UserRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class OrderService {
    private final OrderMapper mapper;
    private final UserRedisUtils userRedisUtils;

    public OrderService(OrderMapper mapper, UserRedisUtils userRedisUtils) {
        this.mapper = mapper;
        this.userRedisUtils = userRedisUtils;
    }

    public OrderVO getOrders(int pageNumber, int pageSize, int orderStatus) {
        Page<Order> page = new Page<>(pageNumber, pageSize);
        Page<Order> orderPage;
        if (orderStatus != -2) {
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_status", orderStatus);
            orderPage = mapper.selectPage(page, wrapper);
        } else {
            orderPage = mapper.selectPage(page, null);
        }
        List<Order> records = orderPage.getRecords();
        return new OrderVO(orderPage.getTotal(), pageNumber, records);
    }

    public boolean addOrder(Order order) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        log.info("addOrder:{}", order);
        order.setCustomerId(userRedisUtils.getUserId());
        int insert = mapper.insert(order);
        return insert > 0;
    }

    public ResponseEntity<Response> editOrder(int state, int[] ids) {
        for (int id : ids) {
            Order order = mapper.selectByOrderId(id);
            System.out.println("id:" + order);
            order.setOrderStatus(state);
            if (state == 4) order.setCompletedDate(new Date());
            mapper.updateById(order);
        }
        Response response = new Response();
//        if (update == 0) {
//            response.setResultCode(500);
//            response.setMessage("修改失败");
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
//        } else {
        response.setResultCode(200);
        response.setMessage("修改成功");
        return ResponseEntity.ok().body(response);
//        }
    }
}
